/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 * Description: tee_log.c
 */

#include "infra/log/ai_log.h"

#include <stdarg.h>

#include "securec.h"
#include "tee_log.h"
#include "infra/base/api_export.h"

#define LOG_BUFFER_SIZE 2048

static const char* g_LogLevels[AI_LOG_ID_MAX] = {
    TAG_DEBUG, // AI_LOG_DEBUG
    TAG_INFO, // AI_LOG_INFO
    TAG_WARN, // AI_LOG_WARN
    TAG_ERROR, // AI_LOG_ERROR
};

INFRA_API_EXPORT __attribute__((__format__(__printf__, 3, 4))) void AI_Log_Print(
    AI_LogPriority priority, const char* moduleName, const char* fmt, ...)
{
    if (priority < AI_LOG_DEBUG || priority > AI_LOG_ERROR) {
        return;
    }

    char logBuffer[LOG_BUFFER_SIZE] = {0};
    int index = 0;

    int ret = snprintf_s(logBuffer, LOG_BUFFER_SIZE, LOG_BUFFER_SIZE - 1, "%s %s ", g_LogLevels[priority], moduleName);
    if ((ret < 0) || (ret >= (LOG_BUFFER_SIZE - 1))) {
        return;
    }
    index += ret;

    va_list arg;
    va_start(arg, fmt);
    ret = vsnprintf_s(logBuffer + index, LOG_BUFFER_SIZE - index, LOG_BUFFER_SIZE - index - 1, fmt, arg);
    va_end(arg);
    if (ret < 0) {
        return;
    }
    // 默认日志级别为INFO
    if (priority == AI_LOG_ERROR) {
        tee_print(LOG_LEVEL_ERROR, "%s", logBuffer);
    } else {
        tee_print(LOG_LEVEL_ON, "%s", logBuffer);
    }
}
